package cn.com.dhcc.turbo.service.monitor.gather;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.app.pub.core.util.HttpUtil;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.tlq.TlqLq;
import cn.com.dhcc.turbo.entity.registry.tlq.TlqSq;
import cn.com.dhcc.turbo.service.monitor.MonitorService;
import cn.com.dhcc.turbo.service.monitor.QUOTA;
import cn.com.dhcc.turbo.service.queue.tlq.TlqOptService;
import cn.com.dhcc.turbo.service.queue.tlq.TlqQueueService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.NodePipelineService;
import cn.com.dhcc.turbo.service.registry.vo.PipeLineTlq;
/**
 * tlq指标收集
 */
@Service
public class TlqGatherService {
	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(Log.LOGTYPE.MONITOR);
	@Autowired
	@Qualifier(AppIocBean.BASE_INFO_SERVICEIMPL_BEAN)
	BaseInfoService baseInfoService;
	@Autowired
	MonitorService monitorService;
	@Autowired
	TlqOptService tlqOptService;
	@Autowired
	TlqQueueService tlqQueueService;
	@Autowired
	NodeInfoService nodeInfoService;
	@Autowired
	private NodePipelineService nodePipelineService;
	
	
	/**
	 * 计算TLQ状态
	 *//*
	public void localTonglingkqConnStatus() {
		QUOTA quota = QUOTA.LOCAL_TLQ_CONN_STATUS;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			String status = "";
			String msg = "";
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			Status qcuStatus = tlqOptService.getQCUState();
			if (qcuStatus.isSuccess()) {
				status = (String) qcuStatus.getData();
				msg = qcuStatus.getMsg();
			} else {
				status = "error";
				msg = qcuStatus.getMsg();
			}
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(nodeInfo.getId());
			onTime.setCurrentValue1(status);
			onTime.setRemark(msg);
			monitorService.insertQuotaOnTime(onTime);
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	
	
	*//**
	 * 计算TLQ 创建本地队列的最大消息数
	 *//*
	public void localTlqDyLqMsgNum() {
		QUOTA quota = QUOTA.LOCAL_TLQ_DY_LQ_MSG_NUM;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			String msgNum = "";
			String msg = "";
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			Status qcuStatus = tlqOptService.getQCUVO();
			if (qcuStatus.isSuccess()) {
				TlqQcu tlqQcu = (TlqQcu) qcuStatus.getData();
				msg = qcuStatus.getMsg();
				msgNum = StrUtil.fixNull(tlqQcu.getDyLocalQueMsgNum());
			} else {
				msgNum = "error";
				msg = qcuStatus.getMsg();
			}
			
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(nodeInfo.getId());
			onTime.setCurrentValue1(msgNum);
			onTime.setRemark(msg);
			monitorService.insertQuotaOnTime(onTime);
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	
	*//**
	 * 计算TLQ 创建发送队列的最大消息数
	 *//*
	public void localTlqDySqMsgNum() {
		QUOTA quota = QUOTA.LOCAL_TLQ_DY_SQ_MSG_NUM;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			String msgNum = "";
			String msg = "";
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			Status qcuStatus = tlqOptService.getQCUVO();
			if (qcuStatus.isSuccess()) {
				TlqQcu tlqQcu = (TlqQcu) qcuStatus.getData();
				msg = qcuStatus.getMsg();
				msgNum = StrUtil.fixNull(tlqQcu.getDySendQueMsgNum());
			} else {
				msgNum = "error";
				msg = qcuStatus.getMsg();
			}
			
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(nodeInfo.getId());
			onTime.setCurrentValue1(msgNum);
			onTime.setRemark(msg);
			monitorService.insertQuotaOnTime(onTime);
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	
	
	*//**
	 * 计算TLQ 本地队列数据存储区预留空间
	 *//*
	public void localTlqDyLqDataBuff() {
		QUOTA quota = QUOTA.LOCAL_TLQ_DY_LQ_DATA_BUFF;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			String msgNum = "";
			String msg = "";
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			Status qcuStatus = tlqOptService.getQCUVO();
			if (qcuStatus.isSuccess()) {
				TlqQcu tlqQcu = (TlqQcu) qcuStatus.getData();
				msg = qcuStatus.getMsg();
				msgNum = StrUtil.fixNull(tlqQcu.getDyLocalQueDataBuff());
			} else {
				msgNum = "error";
				msg = qcuStatus.getMsg();
			}
			
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(nodeInfo.getId());
			onTime.setCurrentValue1(msgNum);
			onTime.setRemark(msg);
			monitorService.insertQuotaOnTime(onTime);
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	
	
	*//**
	 * 计算TLQ 发送队列数据存储区预留空间
	 *//*
	public void localTlqDySqDataBuff() {
		QUOTA quota = QUOTA.LOCAL_TLQ_DY_SQ_DATA_BUFF;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			String msgNum = "";
			String msg = "";
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			Status qcuStatus = tlqOptService.getQCUVO();
			if (qcuStatus.isSuccess()) {
				TlqQcu tlqQcu = (TlqQcu) qcuStatus.getData();
				msg = qcuStatus.getMsg();
				msgNum = StrUtil.fixNull(tlqQcu.getDySendQueDataBuff());
			} else {
				msgNum = "error";
				msg = qcuStatus.getMsg();
			}
			
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(nodeInfo.getId());
			onTime.setCurrentValue1(msgNum);
			onTime.setRemark(msg);
			monitorService.insertQuotaOnTime(onTime);
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	*//**
	 * 计算TLQ 本地TonlinkQ未成功创建的队列数
	 *//*
	public void localTlqNotCreateQueue() {
		QUOTA quota = QUOTA.LOCAL_TLQ_NOT_CREATE_QUEUE;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		int errorNum = 0;
		try {
			List<TlqLq> lqList = tlqQueueService.getRecvQueueList();
			List<TlqSq> sqList = tlqQueueService.getSendQueueList();
			if(CollectionUtil.hasElement(sqList)){
				for (Iterator<TlqSq> iterator = sqList.iterator(); iterator.hasNext();) {
					TlqSq tlqSq =  iterator.next();
					if(tlqSq.getIsQueueExist()==YESNO.NO.getStatus()){
						errorNum++;
					}
				}
			}
			if(CollectionUtil.hasElement(lqList)){
				for (Iterator<TlqLq> iterator2 = lqList.iterator(); iterator2.hasNext();) {
					TlqLq tlqSq =  iterator2.next();
					if(tlqSq.getIsQueueExist()==YESNO.NO.getStatus()){
						errorNum++;
					}
				}
			}
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(nodeInfo.getId());
			onTime.setCurrentValue1(errorNum+"");
			monitorService.insertQuotaOnTime(onTime);
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + errorNum);
	}*/
	
	/**
	 * 计算TLQ状态
	 */
	public void tonglingkqConnStatus() {
		QUOTA quota = QUOTA.TONGLINGKQ_CONN_STATUS;
		QUOTA remoteQuota = QUOTA.REMOTE_TONGLINGKQ_CONN_STATUS;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			String status = "0";
			String msg = "";
			String alertMsg = "";
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			if(localNode==null){
				logger.error("收集指标[" + quota.getDesc() + "]失败:节点未初始化");
				return;
			}
//			NodeInfo pNode = nodeInfoService.get(localNode.getPid());
			List<NodeInfo> list = nodeInfoService.getAllLocalExchNodeList(localNode.getId());
			if(list.size() == 0){
				list.add(localNode);
			}
			for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
				NodeInfo nodeInfo = iterator.next();
				QuotaValueOnTime onTime = new QuotaValueOnTime();
				onTime.setMtime(new Date());
				onTime.setId(UUIDGenerator.getUUID());
				onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
				 if(HttpUtil.checkUrl(nodeInfo.getInstallUrl()))	 {
					 if(localNode.getId().equals(nodeInfo.getId())){
							Status qcuStatus = tlqOptService.getAllQCUState();
							if (qcuStatus.isSuccess() && "Working".equals((String)qcuStatus.getData())) {
								status = "1";
							} else {
								status = "0";
							}
						}else{
							PipeLineTlq tlq = nodePipelineService.getTlqPipeLineByNodeCode(nodeInfo.getNodeCode());
							if(tlq == null)continue;
							if(nodeInfoService.checkServerUrl(tlq.getBrokerIp()+":"+tlq.getJmsPort()) || !nodeInfoService.checkServerUrl(tlq.getBrokerIp()+":"+tlq.getSupervisePort())){
								status = "1";
							}
						}
				 }else{
					 status = "1";
				 }
				 if(localNode.getId().equals(nodeInfo.getId())){
						onTime.setOwnerId(nodeInfo.getId());
						onTime.setQuotaCode(quota.getCode());
				}else{
						onTime.setOwnerId(localNode.getId()+"|"+nodeInfo.getId());
						onTime.setQuotaCode(remoteQuota.getCode());
				}
				onTime.setAlertMsg(alertMsg);
				onTime.setCurrentValue1(status);
				onTime.setRemark(msg);
				monitorService.insertQuotaOnTime(onTime);
				logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
			}
		} catch (Exception e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
	}
	/**
	 * TonlinkQ队列个数
	 */
	/**
	public void tonglingkqQueueNum() {
		QUOTA quota = QUOTA.TONGLINGKQ_QUEUE_NUM;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			if(localNode==null){
				logger.error("收集指标[" + quota.getDesc() + "]失败:节点未初始化");
				return;
			}
			List<TlqLq> lqList = tlqQueueService.getRecvQueueList();
			List<TlqSq> sqList = tlqQueueService.getSendQueueList();
//			NodeInfo pNode = nodeInfoService.get(localNode.getPid());
			num = lqList.size()+sqList.size();
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setNeedAlert("0");
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(localNode.getId());
			onTime.setCurrentValue1(""+num);
			monitorService.insertQuotaOnTime(onTime);
		} catch (Exception e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	 */
	/**
	 * TonlinkQ异常队列数
	 */
	public void tonglingkqQueueStatus() {
		QUOTA quota = QUOTA.TONGLINGKQ_QUEUE_STATUS;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			if(localNode==null){
				logger.error("收集指标[" + quota.getDesc() + "]失败:节点未初始化");
				return;
			}
			List<TlqLq> lqList = tlqQueueService.getRecvQueueList();
			List<TlqSq> sqList = tlqQueueService.getSendQueueList();
			String value = "1";
			if (null == lqList || lqList.size() == 0){
				value = "0";
			}
			for (Iterator<TlqLq> iterator = lqList.iterator(); iterator.hasNext();) {
				TlqLq lq = iterator.next();
				if(!"Working".equals(lq.getStatus())){
					value = "0";
					break;
				}
			}
			for (Iterator<TlqSq> iterator = sqList.iterator(); iterator.hasNext();) {
				TlqSq sq = iterator.next();
				if(!"Working".equals(sq.getStatus())){
					if(value.equals("0")){
						break;
					}
					value = "0";
					break;
				}
			}
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(localNode.getId());
			onTime.setCurrentValue1(value);
			monitorService.insertQuotaOnTime(onTime);
		} catch (Exception e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束");
	}
	
	/**
	 * TonlinkQ队列消息数使用率
	 */
	public void tonglingkqQueueMsgnumRate() {
		QUOTA quota = QUOTA.TONGLINGKQ_QUEUE_MSGNUM_RATE;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			if (localNode==null){
				logger.error("收集指标[" + quota.getDesc() + "]失败:节点未初始化");
				return;
			}
//			NodeInfo pNode = nodeInfoService.get(localNode.getPid());
			List<TlqLq> lqList = tlqQueueService.getRecvQueueList();
			List<TlqSq> sqList = tlqQueueService.getSendQueueList();
			int rate = 0;
			int tempRate = 0;
			for (Iterator<TlqLq> iterator = lqList.iterator(); iterator.hasNext();) {
				TlqLq lq = iterator.next();
				if("Working".equals(lq.getStatus())){
					int usedMsgNum = Integer.parseInt(lq.getUsedMsgNum());
					int configMsgNum = Integer.parseInt(lq.getConfigMsgNum());
					rate = (int) Math.round(Math.floor(usedMsgNum/configMsgNum*100));
					if(rate >tempRate){
						tempRate = rate;
					}
				}
			}
			for (Iterator<TlqSq> iterator = sqList.iterator(); iterator.hasNext();) {
				TlqSq sq = iterator.next();
				if("Working".equals(sq.getStatus())){
					int usedMsgNum = Integer.parseInt(sq.getUsedMsgNum());
					int configMsgNum = Integer.parseInt(sq.getConfigMsgNum());
					rate = (int) Math.round(Math.floor(usedMsgNum/configMsgNum*100));
					if(rate >tempRate){
						tempRate = rate;
					}
				}
			}
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setQuotaCode(quota.getCode());
			onTime.setMtime(new Date());
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER.getCode());
			onTime.setOwnerId(localNode.getId());
			onTime.setCurrentValue1(""+tempRate);
			monitorService.insertQuotaOnTime(onTime);
		} catch (Exception e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
}
